package top.wilsonlv.jaguar.cloud.auth.oauth2;

import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

/**
 * @author lvws
 * @since 2022/3/30 0030
 */
public class ResourceOwnerPasswordCaptchaTokenGranter extends ResourceOwnerPasswordTokenGranter {

    private static final String GRANT_TYPE = "password_captcha";

    private final CaptchaService captchaService;

    public ResourceOwnerPasswordCaptchaTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
                                                    ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, CaptchaService captchaService) {
        super(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.captchaService = captchaService;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        String captchaVerification = tokenRequest.getRequestParameters().get("captchaVerification");

        CaptchaVO captcha = new CaptchaVO();
        captcha.setCaptchaVerification(captchaVerification);
        ResponseModel responseModel = captchaService.verification(captcha);

        if (!responseModel.isSuccess()) {
            throw new InvalidGrantException(responseModel.getRepMsg());
        }

        return super.getOAuth2Authentication(client, tokenRequest);
    }
}
